package com.qs.realm;

import com.qs.pojo.SysUser;
import com.qss.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * @Description
 * @user HP
 * @email 1460961774@qq.com
 * @Date 2021-10-04 19:50
 * @packageName com.qs.realm
 */
public class UserRealm extends SimpleAccountRealm {

    private UserService userService;
    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        String loginName = userToken.getUsername();
        String loginPwd = new String(userToken.getPassword());
        // 进行手动身份认证
        SysUser user = userService.queryUserByUserName(loginName);
        if(user==null){
            throw new UnknownAccountException();
        }else{
            if(user.getStatus()==1){
                throw new DisabledAccountException();
            }

        }
        ByteSource byteSource = ByteSource.Util.bytes(loginName);

        /**
         * 参数1： 当前登录的用户的用户名
         * 参数2： 从数据库中查询到的加密
         * 参数3：加密的盐值
         * 参数4： realm的名称
         */
        return new SimpleAuthenticationInfo(token.getPrincipal(),user.getLoginPwd(),byteSource,getName());
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String loginName = principals.getPrimaryPrincipal().toString();
        SysUser user = userService.queryUserByUserName(loginName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(String.valueOf(user.getRoleId()));
        // 为当前subject添加细粒度的权限
        List<String> permissions =  userService.queryUserPermissionsStr(user);
        info.addStringPermissions(permissions);
        return info;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
